package com.woniu.user.app.apiImpl;

import com.alipay.api.AlipayApiException;
import com.woniu.result.Result;
import com.woniu.user.app.util.WebUtil;
import com.woniu.user.client.UserVIPManageClient;
import com.woniu.user.service.VipService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

@RestController
@Slf4j
public class UserVIPManageApiImpl implements UserVIPManageClient {
    @Resource
    private VipService vipService;
    @Resource
    private RocketMQTemplate rmt;

    /**
     * 购买会员卡
     *
     * @param cardId
     * @return
     */
    @Override
    public Result buyCard(Integer cardId,Integer userId) {

        log.info("查看会员卡Id:{}{}", cardId,userId);
        String cardNum = vipService.buyCard(cardId,userId);
        return Result.getInstance(String.class).setMsg("购买成功").setData(cardNum);

    }

    /**
     * 支付购买会员卡
     *
     * @param cardNum
     * @return
     * @throws Exception
     */
    @Override
    public void payVipCard(String cardNum) throws Exception {
        log.info("查看购买单号:{}", cardNum);
        String result = vipService.payVipCard(cardNum);
        if (result != null) {
            Message<String> msg = MessageBuilder.withPayload(cardNum).build();
            rmt.syncSend("lxlg-find-pay", msg, 5000, 5);
            WebUtil.getResponse().setCharacterEncoding("utf8");
            WebUtil.getResponse().setContentType("text/html;charset=utf8");
            WebUtil.getResponse().getWriter().write(result);
            WebUtil.getResponse().getWriter().flush();
        } else {
            WebUtil.getResponse().sendRedirect("errorpay.html");
        }
//        return Result.getInstance().setMsg("支付成功");
    }

    /**
     * 支付回调
     * @return
     */
    @Override
    public Result payCallback() {
        System.out.println("支付回调:");
        String state = WebUtil.getRequest().getParameter("trade_status");
        if (state != null && state.equals("TRADE_SUCCESS")) {
            String num = WebUtil.getRequest().getParameter("out_trade_no");
            System.out.println("发送消息执行支付成功的逻辑: " + num);
            Message<String> msg = MessageBuilder.withPayload(num).build();
            rmt.syncSend("lxlg-order-payok", msg);
        }
        return Result.getInstance();
    }
}
